package info.cs52.fes;

import info.cs52.fes.action.SessionUtils;

import java.io.IOException;
import java.net.URLEncoder;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FesAction extends HttpServlet {

	protected String title;
	protected String message;
	protected EntityManager em;
	private boolean loginRequired;
	
	@Override
	public void init() throws ServletException {
		super.init();
		loginRequired = "yes".equalsIgnoreCase(getInitParameter("loginRequired"))
				|| "true".equalsIgnoreCase(getInitParameter("loginRequired"));
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		if (loginRequired && !SessionUtils.isLoggedIn(request)) {
			response.sendRedirect(Application.getPath() 
					+ "/auth/login?returnUrl="
					+ URLEncoder.encode(request.getRequestURI(), "UTF-8"));
			return;
		}

		em = Application.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		try {
			message = "";
			request.setAttribute("action", this);
			super.service(request, response);
			if (!response.isCommitted()) {
				request.setAttribute("path", Application.getPath());
				request.setAttribute("servletName", getServletName());
				request.getRequestDispatcher("/index.jsp").forward(request,
						response);
			}
			tx.commit();
		} finally {
			em.close();
		}
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}
	
	public String getMessage() {
		return message;
	}
	
}
